use rusqlite::{params, Connection, Result};

use super::address::Address;
use crate::{ADDRS, GLOBAL_CONFIG};


#[tauri::command]
pub fn edit_addr(id: i64, name: &str, tel: &str, tags: Vec<String>) -> String {
    if name.is_empty() {
        return "姓名不能为空".to_string()
    }
    println!("存储数据");
    update_addr(id, name, tel, &tags).unwrap();
    println!("存储成功");
    // 更新缓存
    let mut addrs = ADDRS.lock().unwrap();
    let addr = Address::new(id, name.to_string(), tel.to_string(), tags);
    addrs.insert(id, addr);
    println!("存储成功");
    "添加成功".to_string()
}

fn update_addr(id: i64, name: &str, tel: &str, tags: &Vec<String>) -> Result<()>{
    let conn = Connection::open(GLOBAL_CONFIG.lock().unwrap().address.db_file.clone()).unwrap();
    conn.execute(
        "UPDATE address SET name = ?1, tel = ?2 WHERE id = ?3",
        params![name, tel, id],
    )?;
    conn.execute("DELETE FROM addr_label WHERE addr_id = ?1", [id])?;
    if tags.len() > 0 {
        for tag in tags {
            // 先查询是否已存在该label，不存在时再插入
            let mut stmt = conn.prepare("SELECT id FROM label WHERE label = ?1")?;
            let exist_label_id = stmt.query_row([tag], |row| row.get(0));

            let label_id;
            if exist_label_id.is_ok() {
                label_id = exist_label_id.unwrap();
            } else {
                conn.execute("INSERT INTO label (label) VALUES (?1)", [tag])?;
                label_id = conn.last_insert_rowid();
            }
            conn.execute("INSERT INTO addr_label (addr_id, label_id) VALUES (?1, ?2)", [id, label_id])?;
        }

        // 删除不再使用的tag
        conn.execute("
            DELETE FROM label 
            WHERE id IN (
            SELECT id FROM label l 
            LEFT JOIN addr_label al ON l.id = al.label_id 
            WHERE al.label_id IS NULL )
        ", [])?;
    }
    Ok(())
}